#!/usr/bin/env python3

"""
转化json为单一的url,并保存在文件
"""

import json
import sys

G_ENVS = {
        'base_url': 'https://b.jaja.cc/api',
        'token': 'bardacoolcoolcool',
        'female': '0',
        'male': '1',
        'page': '1',
        'page_size': '10',
        'longitude': '100.23943',
        'latitude': '26.87226',
}

def load_data(filename):
    """
    加载json数据
    """
    try:
        with open(filename, 'r') as fp:
            data = json.load(fp)
        return data
    except Exception as err:
        return None

def load_envData(env_data):
    envs = {}
    for it in env_data['values']:
        env_key = it['key']
        env_value = it['value']
        envs[env_key] = env_value
    return envs

def urlReplace(collection, env_data, urls_file):
    """
    将环境变量替换掉初始url语句,并将新生成的url写入新文件中
    """
    envs = load_envData(env_data)
    for it in collection['item']:
        url = it['request']['url']['raw']
        #  替换全局变量
        for k,v in G_ENVS.items():
            url = url.replace("{{%s}}" % k, v)
        #  替换用户变量
        #  for k,v in envs.items():
            #  url = url.replace("{{%s}}" % k, v)
        print(url, file=open(urls_file, 'a+'))


if __name__ == "__main__":
    collection_file = sys.argv[1]
    urls_file = sys.argv[2]
    collection = load_data(collection_file)
    env_data = load_data('env.json')
    urlReplace(collection, env_data, urls_file)
